package com.alita.redis.service;

import com.alita.redis.utils.dingding.DingtalkUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;

import java.util.HashSet;
import java.util.Set;

@Service
public class RedisService {

    @Autowired
    private RedisTemplate redisTemplate;

    public void scanKey(String matchKey){
        Set<String> keys = new HashSet<>(10000 * 100);
        int count = 2000;
        ScanResult<String> result = scanKeys(0, count, matchKey);
        keys.addAll(result.getResult());
        int newCursor = result.getCursor();
        while (newCursor != 0){
            result = scanKeys(newCursor,count, matchKey);
            newCursor = result.getCursor();
            keys.addAll(result.getResult());
        }
        Set<String> persistKeys = new HashSet<>(2000);
        keys.forEach(key -> {
            Long ttl = ttl(key);
            if (ttl == -1){
                persistKeys.add(key);
            }
        });
        if (persistKeys.size() > 0){
            StringBuilder sb = new StringBuilder().append("含有 ").append(matchKey).append(" 永不过期的key为:\n\n");
            persistKeys.forEach(key -> {
                sb.append(key);
                sb.append("\n");
            });
            // DingtalkUtil.sendDingMessage(sb.toString(),null);
        }
        keys = null;
    }

    private ScanResult<String> scanKeys(int cursor, int count, String matchKey) {
        return (ScanResult<String>)redisTemplate.execute((RedisCallback<ScanResult<String>>) connection -> {
            Jedis jedis = (Jedis) connection.getNativeConnection();
            ScanParams scanParams = new ScanParams();
            scanParams.match(matchKey);
            scanParams.count(count);
            return jedis.scan(cursor, scanParams);
        });
    }

    public Long ttl(String key) {
        return (long)redisTemplate.execute((RedisCallback<Long>) connection -> {
            Jedis jedis = (Jedis) connection.getNativeConnection();
            return jedis.ttl(key);
        });
    }

}
